﻿using Enyim.Caching;
using Enyim.Caching.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DotNetMVC.OA.Common.Cache
{
   public class MemcacheWriter:ICacheWriter
    {
        private MemcachedClient memcachedClient;
        public MemcacheWriter()
        {
            //string[] servers = { "192.168.1.100:11211", "192.168.1.118:11211" };

            string strAppMemcachedServer = System.Configuration.ConfigurationManager.AppSettings["MemcachedServerList"];

            string[] servers = strAppMemcachedServer.Split(',');

            MemcachedClientConfiguration mcConfig = new MemcachedClientConfiguration();
            //mcConfig.AddServer("127.0.0.1:11211");//必须指定端口
            foreach (string server in servers)
            {
                mcConfig.AddServer(server);//必须指定端口
            }
            memcachedClient = new MemcachedClient(mcConfig);
        }


        public void AddCache(string key, object value, DateTime expDate)
        {
            memcachedClient.Store(Enyim.Caching.Memcached.StoreMode.Add, key, value, expDate);
        }

        public void AddCache(string key, object value)
        {
            memcachedClient.Store(Enyim.Caching.Memcached.StoreMode.Add, key, value);
        }

        public object GetCache(string key)
        {
            return memcachedClient.Get(key);
        }

        public T GetCache<T>(string key)
        {
            return (T)memcachedClient.Get(key);
        }


        public void SetCache(string key, object value, DateTime expDate)
        {
            memcachedClient.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value, expDate);
        }

        public void SetCache(string key, object value)
        {
            memcachedClient.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value);
        }
    }
}
